<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="所属班级">
            <el-tree-select
                v-model="queryParams.belongId"
                :data="classOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="classId"
                placeholder="请选择班级"
                check-strictly
                default-expand-all
            />
          </el-form-item>
          <el-form-item label="所属级别" prop="gradeLevel">
            <el-select v-model="queryParams.gradeLevel" placeholder="请选择" clearable>
              <el-option v-for="dict in school_grade_level" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="学生状态" prop="studentStatus">
            <el-select v-model="queryParams.studentStatus" placeholder="请选择学生状态" clearable>
              <el-option v-for="dict in student_school_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="放行状态" prop="permitStatus">
            <el-select v-model="queryParams.permitStatus" placeholder="请选择放行状态" clearable>
              <el-option v-for="dict in student_leave_permit_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态" prop="auditStatus">
            <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable>
              <el-option v-for="dict in student_leave_audit_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="请假时间" style="width: 480px">
            <el-date-picker
              v-model="dateRangeLeaveTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              clearable
            />
          </el-form-item>
          <el-form-item label="申请时间" style="width: 480px">
            <el-date-picker
              v-model="dateRangeApplyTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['attendance:studentLeave:add']">新增</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['attendance:studentLeave:edit']">修改</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['attendance:studentLeave:remove']">删除</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['attendance:studentLeave:export']">导出</el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        height="calc(100vh - 470px)"
        v-loading="loading"
        :data="studentLeaveList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row: any, column: any, event: Event) => handleUpdate(row)"
      >
        <el-table-column label="学生姓名" align="center" prop="studentName" />
        <el-table-column label="班级名称" align="center" prop="className" />
        <el-table-column label="住宿类型" align="center" prop="accommodationType">
          <template #default="scope">
            <dict-tag :options="student_accommodation_type" :value="scope.row.accommodationType" />
          </template>
        </el-table-column>
        <el-table-column label="请假时间" align="center" width="180">
          <template #default="scope">
            <span>{{ scope.row.startTime }}</span>
            <span style="padding-left: 10px; padding-right: 10px">至</span>
            <span>{{ scope.row.endTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="请假时长（小时）" align="center" prop="leaveDuration" />
        <el-table-column label="审核状态" align="center" prop="auditStatus">
          <template #default="scope">
            <dict-tag :options="student_leave_audit_status" :value="scope.row.auditStatus" />
          </template>
        </el-table-column>
        <el-table-column label="审批意见" align="center" prop="auditOpinion" />
        <el-table-column label="请假类型" align="center" prop="leaveType">
          <template #default="scope">
            <dict-tag :options="leave_type" :value="scope.row.leaveType" />
          </template>
        </el-table-column>
        <el-table-column label="请假事由" align="center" prop="leaveReason" />
        <el-table-column label="接送方式" align="center" prop="shuttleWay" />
        <el-table-column label="监护人姓名" align="center" prop="guardianName" />
        <el-table-column label="班主任姓名" align="center" prop="staffName" />
        <el-table-column label="学生状态" align="center" prop="studentStatus">
          <template #default="scope">
            <dict-tag :options="student_school_status" :value="scope.row.studentStatus" />
          </template>
        </el-table-column>
        <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
          <template #default="scope">
            <span>{{ scope.row.applyTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="签名图片" align="center" prop="signPic" width="100">
          <template #default="scope">
            <image-preview :src="scope.row.signPic" :width="50" :height="50" />
          </template>
        </el-table-column>
        <!--        <el-table-column label="审批时间" align="center" prop="auditTime" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d}') }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="放行状态" align="center" prop="permitStatus">
          <template #default="scope">
            <dict-tag :options="student_leave_permit_status" :value="scope.row.permitStatus" />
          </template>
        </el-table-column>
        <el-table-column label="放行时间" align="center" prop="permitTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.permitTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['attendance:studentLeave:edit']"
                ><el-icon><View /></el-icon
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改学生请假对话框 -->
    <StudentLeaveDetailDialog ref="studentLeaveDetailDialogRef" />
  </div>
</template>

<script setup name="StudentLeave" lang="ts">
import { listStudentLeave, getStudentLeave, delStudentLeave, addStudentLeave, updateStudentLeave } from '@/api/attendance/leave/student';
import { StudentLeaveVO, StudentLeaveQuery, StudentLeaveForm } from '@/api/attendance/leave/student/types';
import { classTree, listClassInfo } from '@/api/office/class';
import StudentLeaveDetailDialog from "./modules/StudentLeaveDetailDialog";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { student_leave_permit_status, student_accommodation_type, leave_type, student_school_status, student_leave_audit_status, school_grade_level } =
  toRefs<any>(
    proxy?.useDict(
      'student_leave_permit_status',
      'student_accommodation_type',
      'leave_type',
      'student_school_status',
      'student_leave_audit_status',
      'school_grade_level'
    )
  );

const studentLeaveList = ref<StudentLeaveVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeLeaveTime = ref<[DateModelType, DateModelType]>(['', '']);
const dateRangeApplyTime = ref<[DateModelType, DateModelType]>(['', '']);
const dateRangePermitTime = ref<[DateModelType, DateModelType]>(['', '']);
const classOptions = ref<any[]>([]);
const queryFormRef = ref<ElFormInstance>();
const studentLeaveDetailDialogRef = ref();

const initFormData: StudentLeaveForm = {
  id: undefined,
  studentId: undefined,
  studentName: undefined,
  classId: undefined,
  className: undefined,
  studentStatus: undefined,
  accommodationType: undefined,
  startTime: undefined,
  endTime: undefined,
  leaveDuration: undefined,
  auditStatus: undefined,
  auditOpinion: undefined,
  leaveType: undefined,
  leaveReason: undefined,
  shuttleWay: undefined,
  guardianId: undefined,
  guardianName: undefined,
  signPic: undefined,
  staffId: undefined,
  staffName: undefined,
  applyTime: undefined,
  auditTime: undefined,
  permitStatus: undefined,
  permitTime: undefined
};
const data = reactive<PageData<StudentLeaveForm, StudentLeaveQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentName: undefined,
    classId: undefined,
    gradeLevel: undefined,
    studentStatus: undefined,
    accommodationType: undefined,
    startTime: undefined,
    endTime: undefined,
    leaveDuration: undefined,
    auditStatus: undefined,
    leaveType: undefined,
    shuttleWay: undefined,
    permitStatus: undefined,
    params: {
      applyTime: undefined,
      auditTime: undefined,
      permitTime: undefined
    }
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

const getClassTree = async () => {
  const res = await classTree();
  classOptions.value = res.data;
};

/** 查询学生请假列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeLeaveTime.value, 'LeaveTime');
  proxy?.addDateRange(queryParams.value, dateRangeApplyTime.value, 'ApplyTime');
  const res = await listStudentLeave(queryParams.value);
  studentLeaveList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeLeaveTime.value = ['', ''];
  dateRangeApplyTime.value = ['', ''];
  dateRangePermitTime.value = ['', ''];
  queryParams.value.classId = undefined;
  queryParams.value.className = undefined;
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: StudentLeaveVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {

};

/** 修改按钮操作 */
const handleUpdate = async (row?: StudentLeaveVO) => {
  const _id = row?.id || ids.value[0];
  studentLeaveDetailDialogRef.value.handleUpdate(_id);
};

/** 删除按钮操作 */
const handleDelete = async (row?: StudentLeaveVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除学生请假编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delStudentLeave(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'attendance/studentLeave/export',
    {
      ...queryParams.value
    },
    `studentLeave_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getClassTree();
  getList();
});
</script>
